#include "stdafx.h"
#include "Grid.h"

Grid::Grid(void)
{
}

Grid::~Grid(void)
{
}

void Grid::Init(unsigned int width, unsigned int height, unsigned int square_width, unsigned int square_height)
{
	m_width = width;
	m_height = height;
	m_square_width = square_width;
	m_square_height = square_height;

	Vector3 position = Vector3(0, 0, 0);
	
	for (unsigned int z = 0; z < height; z++)
	{
		for (int x = 0; x < width; x++)
		{
			//calculate the center of the square
			Vector3 center;
			center.x = (position.x + (float)square_width * 0.5f);
			center.y = 0;
			center.z = (position.z + (float)square_height * 0.5f);

			//Create a new square
			Square* square = new Square();
			square->m_position = center;
			square->m_state = ESquareState::none;
			square->m_x = x;
			square->m_y = z;

			//Add the square to the vector
			m_squares.push_back(square);

			//Jump to the next column
			position.x += square_width;
		}
		//Jump to the next row
		position.x = 0;
		position.z += square_width;
	}
}

void Grid::Shut()
{
	for (unsigned int i = 0; i < m_squares.size(); i++)
	{
		delete m_squares[i];
		m_squares[i] = nullptr;
	}
	m_squares.clear();
}

Grid::Square& Grid::GetSquare(unsigned int x, unsigned int y) 
{
	for (unsigned int i = 0; i < m_squares.size(); i++)
	{
		if (m_squares[i]->m_x == x && m_squares[i]->m_y == y)
			return *m_squares[i];
	}
	Square square;
	return square;
}

Grid::Square& Grid::GetSquare(Vector3 position) 
{
	for (unsigned int i = 0; i < m_squares.size(); i++)
	{
		float right = (m_squares[i]->m_position.x + (float)m_square_width * 0.5f);
		float left = (m_squares[i]->m_position.x - (float)m_square_width * 0.5f);
		float top = (m_squares[i]->m_position.z + (float)m_square_height * 0.5f);
		float bottom = (m_squares[i]->m_position.z - (float)m_square_height * 0.5f);

		if (position.x < right && position.x > left && 
			position.z < top && position.z > bottom)
			return *m_squares[i];
	}
	Square square;
	return square;
}

void Grid::SetState(Square* square, ESquareState state)
{
	square->m_state = state;
}